package com.lq.schoolshop.util;

import com.lq.schoolshop.pojo.AopModel;
import com.lq.schoolshop.service.AopLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author
 * @Date2020/8/15 8:59
 * @Version V1.0
 * 日志记录
 **/
@Aspect
@Component
public class AopUtil {
    private static AopModel aopModel = new AopModel();

    @Autowired
    private AopLogService aopLogService;

    private long statimr;

    private long endtime;

    @Pointcut(value = "execution (public * com.lq.schoolshop.controller.before.ForPaymentController.*(..))")
    public void log() {
        System.out.println("所有的数据在这里" + aopModel.toString());
    }

    @Before(value = "log()")
    public void doBefore(JoinPoint joinPoint) {
        statimr = System.currentTimeMillis();
        //接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        aopModel.setUrl(request.getRequestURL().toString());
        aopModel.setHttpmethod(request.getMethod());
        aopModel.setIp(request.getRemoteAddr());
        aopModel.setPath(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        System.out.println(Arrays.toString(joinPoint.getArgs()));
        aopModel.setMethodcount(Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "log()")
    public void doAfterReturning(Object ret) throws Throwable {
        aopModel.setResult(ret.toString());
        endtime = System.currentTimeMillis();
        aopModel.setSpendtime(String.valueOf(endtime - statimr));
        //插入到数据库里面
        aopLogService.insertinfolog(aopModel.getUrl(),aopModel.getHttpmethod(),aopModel.getPath(),aopModel.getResult(),
                aopModel.getSpendtime(),aopModel.getMethodcount());
    }

    //后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
    @After(value = "log()")
    public void doAfter() {
    }

    @AfterThrowing(value = "log()",throwing = "throwable")
    public void afterThrowing(JoinPoint joinPoint,Throwable throwable){
        System.out.println("============异常抛出通知==========="+throwable);
        //插入到错误日志
        aopLogService.inserterrorlog(aopModel.getUrl(),aopModel.getPath(),aopModel.getResult(),aopModel.getMethodcount(),throwable.toString());
    }




}
